package com.webtair.dump4j.producer;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;

import com.webtair.dump4j.core.Item;
import com.webtair.dump4j.objectdump.ObjectDump;

public class ProducerXML implements Producer{
//	ObjectDumpString obj = new ObjectDumpString();
	ObjectDump obj;
	public ObjectDump prepareDump(Item root2, ObjectDump obj) {
		this.obj = obj;
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement(root2.getName());
        root.addAttribute("class",root2.getClassName());
 //       root.addAttribute("value",root2.getValue());
 //       root.addAttribute("id",""+root2.getId());
//        root.addText(root2.getValue())

        List<Item> l = root2.getChildren();
		if(root2.getValue()!=null)
			root.addText(root2.getValue());
		else
			root.addAttribute("id",""+root2.getId());

        for (Iterator iter = l.iterator(); iter.hasNext();) {
			Item element = (Item) iter.next();
			recursivelyAdd(root.addElement(element.getName()),element);
		}
		StringWriter sw = new StringWriter();
		OutputFormat format = OutputFormat.createPrettyPrint();
		org.dom4j.io.XMLWriter writer = new org.dom4j.io.XMLWriter(sw,format);
		try {
			writer.write(document);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		obj.addBlock(sw.getBuffer().toString());
		return obj;
	}

	private void recursivelyAdd(Element el, Item item) {
		el.addAttribute("class",item.getClassName());
	//	el.addAttribute("name",item.getName());

		List<Item> l = item.getChildren();
		if(l.size()>0 || item.isDuplicate()){
			el.addAttribute("id",""+item.getId());
		} else {
			el.addText(item.getValue());
		}

		for (Iterator iter = l.iterator(); iter.hasNext();) {
			Item element = (Item) iter.next();
			recursivelyAdd(el.addElement(element.getName()),element);
		}
	}
}
